added some development tools
[windows-sources.git] / developer / Samples / NET Standard / ParallelExtensionsExtras_Standard / Extensions / APM / WebRequestExtensions.cs
blobc613b114083083d4c5764922b029541453e8e8f4
1 //--------------------------------------------------------------------------
2 //
3 // Copyright (c) Microsoft Corporation. All rights reserved.
4 //
5 // File: WebRequestExtensions.cs
6 //
7 //--------------------------------------------------------------------------
9 using System.IO;
10 using System.Threading.Tasks;
12 namespace System.Net
14 /// <summary>Extension methods for working with WebRequest asynchronously.</summary>
15 public static class WebRequestExtensions
17 /// <summary>Creates a Task that represents an asynchronous request to GetResponse.</summary>
18 /// <param name="webRequest">The WebRequest.</param>
19 /// <returns>A Task containing the retrieved WebResponse.</returns>
20 public static Task<WebResponse> GetResponseAsync(this WebRequest webRequest)
22 if (webRequest == null) throw new ArgumentNullException("webRequest");
23 return Task<WebResponse>.Factory.FromAsync(
24 webRequest.BeginGetResponse, webRequest.EndGetResponse, webRequest /* object state for debugging */);
27 /// <summary>Creates a Task that represents an asynchronous request to GetRequestStream.</summary>
28 /// <param name="webRequest">The WebRequest.</param>
29 /// <returns>A Task containing the retrieved Stream.</returns>
30 public static Task<Stream> GetRequestStreamAsync(this WebRequest webRequest)
32 if (webRequest == null) throw new ArgumentNullException("webRequest");
33 return Task<Stream>.Factory.FromAsync(
34 webRequest.BeginGetRequestStream, webRequest.EndGetRequestStream, webRequest /* object state for debugging */);
37 /// <summary>Creates a Task that respresents downloading all of the data from a WebRequest.</summary>
38 /// <param name="webRequest">The WebRequest.</param>
39 /// <returns>A Task containing the downloaded content.</returns>
40 public static Task<byte[]> DownloadDataAsync(this WebRequest webRequest)
42 // Asynchronously get the response. When that's done, asynchronously read the contents.
43 return webRequest.GetResponseAsync().ContinueWith(response =>
45 return response.Result.GetResponseStream().ReadAllBytesAsync();
46 }).Unwrap();